package com.xiaochun.jiankangapp.base

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.core.app.NotificationChannelCompat
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.bumptech.glide.Glide
import com.tencent.bugly.crashreport.CrashReport
import com.xiaochun.jiankangapp.BuildConfig


class AppContext : Application(), ViewModelStoreOwner {

    private val activities = arrayListOf<Activity>()
    override fun onCreate() {
        _context = this
        super.onCreate()
        CrashReport.initCrashReport(this, "672836bdd5", BuildConfig.DEBUG)
        val h = NotificationChannelCompat.Builder("Task", NotificationManagerCompat.IMPORTANCE_HIGH)
        h.setName("任务提醒")
        NotificationManagerCompat.from(this).let {
            it.createNotificationChannel(h.build())
        }
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                activities.add(activity)
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                activities.remove(activity)
            }
        })
    }

    fun finishAll() {
        activities.forEach {
            it.finish()
        }
    }

    fun <T : Activity> finish(clazz: Class<T>) {
        activities.forEach {
            if (clazz == it::class.java) {
                it.finish()
            }
        }
    }


    override fun attachBaseContext(base: Context?) {
        _context = this
        super.attachBaseContext(base)
    }

    companion object {
        private var _context: AppContext? = null

        @JvmStatic
        fun globalContext(): AppContext {
            return _context!!
        }


    }

    var modelStore: ViewModelStore? = null
    override val viewModelStore: ViewModelStore
        get() = modelStore ?: ViewModelStore().also {
            modelStore = it
        }


    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        Glide.with(this).onTrimMemory(level)
    }

    override fun onLowMemory() {
        super.onLowMemory()
        Glide.with(this).onLowMemory()
    }
}


